package com.xuge.ojwangcodesandbox.controller;

import com.xuge.ojwangcodesandbox.manage.SandboxManager;
import com.xuge.ojwangcodesandbox.model.ExecuteCodeRequest;
import com.xuge.ojwangcodesandbox.model.ExecuteCodeResponse;
import com.xuge.ojwangcodesandbox.services.CodeSandBox;
import com.xuge.ojwangcodesandbox.services.java.JavaNativeCodeSandbox;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.xuge.ojwangcodesandbox.constant.AuthConstant.AUTHREQUESTHEADER;
import static com.xuge.ojwangcodesandbox.constant.AuthConstant.AUTHREQUESTSECRET;

@RestController("/")
public class MainController {
    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                           HttpServletResponse response) {
        String authHeaders = request.getHeader(AUTHREQUESTHEADER);
        //基本认证
        if (!AUTHREQUESTSECRET.equals(authHeaders)) {
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest == null) {
            throw new RuntimeException("参数为空");
        }
        String language = executeCodeRequest.getLanguage();
        CodeSandBox sandBox = SandboxManager.getSandBox(language);
        return sandBox.executeCode(executeCodeRequest);
    }
}